package cn.tedu.straw.portal.service.impl;

import cn.tedu.straw.commons.dto.AnswerDTO;
import cn.tedu.straw.portal.mapper.CommentMapper;
import cn.tedu.straw.portal.mapper.QuestionMapper;
import cn.tedu.straw.commons.model.Answer;
import cn.tedu.straw.portal.mapper.AnswerMapper;
import cn.tedu.straw.commons.model.Question;
import cn.tedu.straw.commons.model.User;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.service.ex.*;
import cn.tedu.straw.commons.vo.AnswerVO;
import cn.tedu.straw.commons.vo.UserCollectionVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-07-28
 */
@Service
@Slf4j
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    @Transactional
    public Answer post(AnswerDTO answerDTO, Integer userId, String userNickName) {


        // 创建Answer对象
        Answer answer = new Answer();
        // 补全answer对象的属性值：content			<<< 参数answerDTO中的content
        answer.setContent(answerDTO.getContent());
        // 补全answer对象的属性值：count_of_likes	<<< 0
        answer.setCountOfLikes(0);
        // 补全answer对象的属性值：user_id			<<< 参数userId
        answer.setUserId(userId);
        // 补全answer对象的属性值：user_nick_name	<<< 参数userNickName
        answer.setUserNickName(userNickName);
        // 补全answer对象的属性值：question_id		<<< 参数answerDTO中的questionId
        answer.setQuestionId(answerDTO.getQuestionId());
        // 补全answer对象的属性值：created_time		<<< 当前时间
        answer.setCreatedTime(LocalDateTime.now());
        // 补全answer对象的属性值：status_of_accept	<<< 0
        answer.setStatusOfAccept(0);
        // 调用int answerMapper.insert(Answer answer)方法插入“回复”的数据，并获取返回结果
        int rows = answerMapper.insert(answer);
        // 判断返回值是否不为1
        if (rows!=1){
            // 是：抛出InsertException
         throw new InsertException("插入失败");
        }
        Integer integer = questionMapper.updateQuestion(answerDTO.getQuestionId(), 1);
        if (integer!=1){
            // 是：抛出InsertException
            throw new UpdateException("修改状态失败");
        }

        return answer;
    }

    @Override
    public List<AnswerVO> getListByQuestion(Integer questionId) {
        return answerMapper.findListByQuestionId(questionId);
    }

    @Override
    public Answer update(Integer id, Integer userId, String content, Integer userType) {

            // 根据参数commentId调用mapper.selectById()查询被修改的“评论”的信息
        Answer result = answerMapper.selectById(id);
            // 判断查询结果是否为null
            if (result == null) {
                // 是：该“评论”不存在，抛出CommentNotFoundException异常
                throw new AnswerNotFoundException("修改回答失败！尝试访问的评论数据不存在！");
            }

            // 基于查询结果中的userId，结合参数userId，判断查询结果数据是否是当前登录用户的，
            // 或基于参数userType，判断当前登录的用户的身份是“老师”，
            if (!result.getUserId().equals(userId) && userType != User.TYPE_TEACHER) {
                // 如果这2个条件都不符合，则不允许修改，抛出PermissionDeniedException
                throw new PermissionDeniedException("修改回答失败！仅发布者和老师可以修改此条评论！");
            }

            // 创建新的Comment comment对象
        Answer answer = new Answer();
            // 将commentId, content封装到comment中
        answer.setId(id);
        answer.setContent(content);
            // 根据comment调用mapper.updateById()执行修改，并获取返回的受影响行数
            int rows = answerMapper.updateById(answer);
            // 判断返回值是否不为1
            if (rows != 1) {
                // 是：抛出UpdateException
                throw new UpdateException("修改回答失败！服务器忙，请稍后再次尝试！");
            }

            // 将content封装到result中
            result.setContent(content);
            // 返回查询结果
            return result;
    }

    @Override
    @Transactional
    public Answer delete(Integer id, Integer userId, Integer userType) {



        // 根据参数answerid调用answerMapper.selectById()查询被删除的“回答”的信息
        Answer answer=answerMapper.selectById(id);
        // 判断查询结果是否为null
        // 是：该“回答”不存在，抛出CommentNotFoundException异常
        if (answer==null){
            throw new CommentNotFoundException("该回答不存在");
        }

        // 基于查询结果中的userId，结合参数userId，判断查询结果数据是否是当前登录用户的，
        // 或基于参数userType，判断当前登录的用户的身份是“老师”，
        // 如果这2个条件都不符合，则不允许删除，抛出PermissionDeniedException

        if (!answer.getUserId().equals(userId)&&userType!= User.TYPE_TEACHER){
            System.err.println("-----------------------------------------");
            throw new PermissionDeniedException("修改回答失败！仅发布者和老师可以修改此条评论！");
        }

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("question_id", answer.getQuestionId());
        Integer integer = answerMapper.selectCount(queryWrapper1);

        if (integer==1){
            Integer integer1 = questionMapper.updateQuestion(answer.getQuestionId(), 0);
            if (integer!=1){
                throw new UpdateException("修改状态失败");
            }
        }



        // 根据参数commentId调用mapper.deleteById()执行查询，并获取返回的受影响行数
        // 判断返回值是否不为1
        // 是：抛出DeleteException
        int rows=answerMapper.deleteById(id);
        if (rows!=1){
            throw new DeleteException("操作回答失败!服务器连接超时!");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("answer_id", id);
        Integer integer2 = commentMapper.selectCount(queryWrapper);
        if (integer2!=0) {

            Integer rows1 = commentMapper.deleteAnswerId(id);
            if (rows1 != 1) {
                throw new DeleteException("操作评论失败!服务器连接超时!");
            }
        }


        // 返回查询结果
        return answer;
    }

    @Value("${project.question-list.page-size}")
    private Integer pageSize;

    @Override
    public PageInfo<Answer> getAnswer(Integer userId, Integer page) {
        //设置分页参数
        PageHelper.startPage(page,pageSize);
        List<Answer> userCollections = answerMapper.findgetAnswer(userId);

        return new PageInfo<Answer>(userCollections);
    }

}
